package com.zhuiyun.project.api.system.login.controller;


import com.zhuiyun.project.annotation.OptLog;
import com.zhuiyun.project.api.system.login.service.impl.SysPermissionService;
import com.zhuiyun.project.api.system.menu.entity.SysMenu;
import com.zhuiyun.project.api.system.menu.service.SysMenuService;
import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.api.system.user.service.SysUserService;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.*;
import com.zhuiyun.project.utils.constants.CommonConstants;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.zhuiyun.project.utils.MailUtils.sendMail;

/**
 * @ClassName SysLoginController
 * @Description TODO
 * @Author lzy
 * @Date 2023/6/16 13:55
 **/
@RestController
public class SysLoginController {


    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserService sysUserService;

    /**
    * @Author Administrator
    * @Description 获取当前登录用户信息
    * @Date 2023/10/26 16:27
    * @Return com.zhuiyun.project.common.response.CommonResult
    */
    @ApiOperation(value = "获取登录用户信息")
    @OptLog(modular = "用户登录", type = CommonConstants.LOGIN, describe = "用户登录操作")
    @GetMapping("getInfo")
    public CommonResult getInfo() throws IOException {
        //getContext拿到SecurityContextHolder的实例对象
        //getAuthentication获取到当前用户的认证信息
        //getPrincipal拿到认证信息中的主体 当前登录用户信息
        SysUser user = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("permissions", permissions);
        return CommonResult.ok(map);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public CommonResult getRouters() {
        Integer userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return CommonResult.ok(menuService.buildMenus(menus));
    }
    /**
     * @Author Administrator
     * @Description 邮箱验证码
     * @Date 2023/11/1 18:54
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @ApiOperation(value = "获取登录用户信息")
    @OptLog(modular = "发送验证码", type = CommonConstants.LOGIN, describe = "发送验证码")
    @PostMapping("/getEmailLogin")
    public CommonResult getEmailLogin(@RequestBody SysUser sysUser) {
        SysUser emailByUser = sysUserService.getUserByEmailAccount(sysUser.getEmail());
        SysUser userByPhoneAccount = sysUserService.getUserByPhoneAccount(sysUser.getPhone());
        //通过前端传递的信息是否存在手机号 判断是登录还是注册
        if (sysUser.getPhone() != null) {
            //注册 判断邮箱账号或手机号是否存在
            if (emailByUser != null || userByPhoneAccount != null) {
                return CommonResult.error("该邮箱或手机号已存在！");
            } else { //不存在 发送验证码
                String emailCode = VerifyCodeUtils.generateVerifyCode(4);
                //发送邮箱
                try {
                    String subject = "验证码";
                    String content = "您的验证码为" + emailCode;
                    //发送验证码
                    sendMail(sysUser.getEmail(), subject, content);
                    //验证码存入redis
                    redisCache.setCacheObject(CommonConstants.CACHE_EMAIL_CODE + emailCode, emailCode, 300, TimeUnit.SECONDS);
                    return CommonResult.ok("您的验证码已发送，请查收!");
                } catch (Exception e) {
                    e.printStackTrace();
                    return CommonResult.error("发送失败！");
                }
            }
        } else { //邮箱登录
            if (emailByUser != null) {
                //判断邮箱账号是否存在 存在之后发送验证码 进行登录操作
                String emailCode = VerifyCodeUtils.generateVerifyCode(4);
                //发送邮箱
                try {
                    String subject = "验证码";
                    String content = "您的验证码为" + emailCode;
                    sendMail(sysUser.getEmail(), subject, content);
                    //验证码存入redis
                    redisCache.setCacheObject(CommonConstants.CACHE_EMAIL_CODE + emailCode, emailCode, 300, TimeUnit.SECONDS);
                    return CommonResult.ok("您的验证码已发送，请查收!");
                } catch (Exception e) {
                    e.printStackTrace();
                    return CommonResult.error("发送失败！");
                }
            }
        }
        return CommonResult.error("邮箱不存在，请前往注册！");
    }

}
